/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo15.controller;

import cn.edu.zua.demo15.entity.DemoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Locale;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/28 16:54
 */
@RestController
public class IndexController {
    private MessageSource messageSource;

    @Autowired
    public IndexController(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @GetMapping(path = "/validator")
    public String validator(@Valid DemoEntity entity, BindingResult result) {
        if (result.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            //获取错误字段集合
            List<FieldError> fieldErrors = result.getFieldErrors();
            //获取本地locale,zh_CN
            Locale currentLocale = LocaleContextHolder.getLocale();
            //遍历错误字段获取错误消息
            for (FieldError fieldError : fieldErrors) {
                //获取错误信息
                String errorMessage = messageSource.getMessage(fieldError, currentLocale);
                //添加到错误消息集合内
                sb.append(fieldError.getField()).append("：").append(errorMessage).append(" , ");
            }
            return sb.toString();
        }
        return "验证通过，" + "名称：" + entity.getName() + "\t年龄：" + entity.getAge() + "\t邮箱地址：" + entity.getMail();
    }

}
